package com.yys.huarongdao.customView;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.GridView;

/**
 * TODO: document your custom view class.
 */
public class MyGridView extends GridView {
    private int tipPosition=-1;
    private OnTipListener onTipListener;
    private boolean STOP_LISTEN=false;

    public MyGridView(Context context) {
        super(context);
        startIsTipThread();
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        startIsTipThread();
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        startIsTipThread();
    }

    public void setTipPosition(int tipPosition) {
        synchronized(this){
            this.tipPosition = tipPosition;
        }
        Log.d("Tip","setTipPosition设置位置");
    }

    public void setOnTipListener(OnTipListener onListener) {
        this.onTipListener = onListener;
        Log.d("Tip","提示setOnTipListener");
    }

    public void destroyIsTipThread(){
        this.STOP_LISTEN=true;
    }

    /**
     *检测提示操作
     * 1、新建线程循环判断tipPosition
     * 2、每100毫秒判断tipPosition是否大于-1。若是大于-1,则执行监听器的监听方法。
     * 3、结束线程
     */
    private void startIsTipThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if (tipPosition > -1) {
                        synchronized(MyGridView.this) {
                            onTipListener.onTip(tipPosition);
                            tipPosition = -1;
                        }
                    }else if(STOP_LISTEN){
                        return;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public interface OnTipListener {
        void onTip(int tipPosition);
    }
}